﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;

namespace VPLink2013.Webpart
{
    [ToolboxItemAttribute(false)]
    public class WebpartVPLink : System.Web.UI.WebControls.WebParts.WebPart
    {
        protected string pathCache = string.Empty;

        protected DateTime dtDateDebutProcess;

        //used for configuration and XSL file
        protected string pathVP = string.Empty;

        //used for path to trace/log file
        protected string pathTemp = string.Empty;

        protected string siteUrl = string.Empty;

        protected string connectionString = string.Empty;

        //current action : new, edit, display, save, search, replace, replaceText
        protected string strAction = string.Empty;

        //this object is serialized as XML (output)
        protected GlobalVPLink2013 global = null;

        //output message (error)
        protected string Message = string.Empty;
        protected string strXslFileName = string.Empty;
        protected StringBuilder sbHtml = new StringBuilder();

        //parametre de la webpart
        private string _sharepointSite = string.Empty;
        protected string strFileCacheUtilisateur = string.Empty;

        protected Utilisateur UtilisateurCrt;


        [Category("Vente privée")]
        [WebDisplayName("Site Sharepoint VP")]
        [WebDescription("Site Sharepoint VP")]
        [WebBrowsable(true)]
        [Personalizable(true)]
        public string ParamSharepointSite
        {
            get
            {
                if (string.IsNullOrEmpty(_sharepointSite))
                    return SPContext.Current.Site.Url;
                return _sharepointSite;
            }
            set
            {
                _sharepointSite = value;
            }
        }

        public WebpartVPLink()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        private void CopyConfigParamsFromCache()
        {
            siteUrl = (string)this.Page.Cache.Get(Fields.ConfigSiteUrlKeyName);
            pathVP = (string)this.Page.Cache.Get(Fields.ConfigVPLayoutsPathKeyName);
            pathTemp = (string)this.Page.Cache.Get("pathTemp");
            pathCache = (string)this.Page.Cache.Get("pathCache");
            connectionString = (string)this.Page.Cache.Get(Fields.ConfigConnectionStringKeyName);
        }

        private void getConfigValues(Dictionary<string, string> configDictionary)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        SPList lstConfig = web.Lists.TryGetList(ListTitles.ConfigurationVPTitle);
                        if (lstConfig != null)
                        {
                            string strValeur = string.Empty;
                            SPListItemCollection coll = lstConfig.GetSPListItemCollectionWithTextFields(new List<string>() { Fields.ConfigKeyField, Fields.ConfigValueField });
                            if (coll != null)
                            {
                                foreach (string key in configDictionary.Keys.ToList())
                                {
                                    SPListItem item = coll.Cast<SPListItem>()
                                        .Where(x => x.GetItemListFieldValueAsText(Fields.ConfigKeyField).Equals(key, StringComparison.CurrentCultureIgnoreCase))
                                        .FirstOrDefault();
                                    if (item != null)
                                    {
                                        strValeur = item.GetItemListFieldValueAsHtml(Fields.ConfigValueField);
                                        configDictionary[key] = strValeur;
                                        this.Page.Cache.Insert(key, strValeur);
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
        private void SetConfigValues()
        {
            try
            {
                Dictionary<string, string> configDictionary = new Dictionary<string, string>()
                { 
                    { Fields.ConfigSiteUrlKeyName, siteUrl},
                    { Fields.ConfigConnectionStringKeyName, connectionString},
                    { Fields.ConfigVPLayoutsPathKeyName, pathVP}
                };
                getConfigValues(configDictionary);

                string _pathVP = configDictionary[Fields.ConfigVPLayoutsPathKeyName];

                pathVP = SPUtility.GetVersionedGenericSetupPath(_pathVP, 15);

                pathTemp = SPUtility.GetVersionedGenericSetupPath(Path.Combine(_pathVP, "Temp"), 15);

                pathCache = SPUtility.GetVersionedGenericSetupPath(Path.Combine(_pathVP, "_Cache"), 15);

                this.Page.Cache.Insert(Fields.ConfigVPLayoutsPathKeyName, pathVP);
                this.Page.Cache.Insert("pathTemp", pathTemp);
                this.Page.Cache.Insert("pathCache", pathCache);
            }
            catch (Exception ex)
            {
                ContextTrace.AddTrace("Exception Lors de la recherche de la version VPLink");
                ContextTrace.AddTrace(ex.StackTrace);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (this.Page.Cache.Get("configValuesInserted") != null)
            {
                CopyConfigParamsFromCache();
            }
            else
            {
                SetConfigValues();
                CopyConfigParamsFromCache();
            }
            base.OnLoad(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                dtDateDebutProcess = DateTime.Now;
                Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR", false);

                ContextTrace.AddTrace("Debut traitement : " + dtDateDebutProcess);

                string CurrentUserTrace = StringAfter(this.Context.User.Identity.Name);

                ContextTrace.AddTrace("conf.Connection.ConnectionString : " + connectionString);
                ContextTrace.AddTrace("conf.CfgSite.Url : " + siteUrl);
                try
                {
                    string strHtml = GetHtml();
                    writer.Write(strHtml);
                    SaveHtmlTrace(strHtml);
                }
                catch (System.Exception exc)
                {
                    ContextTrace.AddTrace("Erreur VPLink2013.RenderWebPart : " + exc.Message + "/" + exc.StackTrace);
                }
                ContextTrace.PathTemp = Path.Combine(pathTemp, CurrentUserTrace);
                ContextTrace.AddTrace("WebPartVPLink2013. Version 1.0.0.0 - 24 mai 2013");

                DateTime dtDateFinProcess = DateTime.Now;
                TimeSpan tsTempsProcess = dtDateFinProcess - dtDateDebutProcess;
                ContextTrace.AddTrace("Fin traitement : " + dtDateFinProcess);
                ContextTrace.AddTrace("Durée traitement : " + tsTempsProcess.TotalMilliseconds.ToString("#,##0"));

            }
            catch (System.Exception exc) 
            {
                ContextTrace.AddTrace("Erreur VPLink2013.RenderWebPart : " + exc.Message + "/" + exc.StackTrace);
            }
            ContextTrace.Save(ContextTrace.PathTemp, ContextTrace.PrefixFileName);
        }

        protected void SetUtilisateurCrt()
        {
            UtilisateurCrt = FileSerialization.CreateObjFromXML<Utilisateur>(strFileCacheUtilisateur);
            if (UtilisateurCrt == null)
            {
                UtilisateurCrt = new Utilisateur();
                UtilisateurCrt.Login = this.Context.User.Identity.Name;
                if (UtilisateurCrt.Login.ToLower() == @"oredis-vp\clrstrm-admmoss"
                || UtilisateurCrt.Login.ToLower() == @"oredis-vp\mpbonazzi")
                {
                    UtilisateurCrt.IsDRH = "1";
                }
                else
                {
                    UtilisateurCrt.IsDRH = "0";
                }
                string strSql = @"SELECT Email
                                         , IsManager
                                         , IsInterimManager
                                         , IsJedi
                                         ,IsEcommerce
                                         ,IsCommercialVoyage
                                         ,IsProductionVoyage
                                         , Site, Pays FROM Users 
                                         WHERE LoginUser = '" + UtilisateurCrt.Login + "'";

                if (!string.IsNullOrEmpty(connectionString))
                {
                    SqlConnection conn = VPLink2013SqlHelper.GetConnection(connectionString);
                    if (conn != null)
                    {
                        SqlCommand command = VPLink2013SqlHelper.GetCommand(conn, strSql);
                        if (command != null)
                        {
                            SqlDataReader Reader = command.ExecuteReader();
                            if (Reader.Read())
                            {
                                UtilisateurCrt.Email = VPLink2013SqlHelper.GetValueReader(Reader, 0);
                                UtilisateurCrt.IsInterne = "1";
                                if (UtilisateurCrt.Email.IndexOf("prestataire") > 0)
                                {
                                    UtilisateurCrt.IsInterne = "0";
                                }
                                if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 1))
                                {
                                    UtilisateurCrt.IsManager = "1";
                                }
                                else
                                {
                                    if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 2))
                                    {
                                        UtilisateurCrt.IsManager = "1";
                                    }
                                }

                                if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 2))
                                {
                                    UtilisateurCrt.IsInterimManager = "1";
                                }
                                if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 3))
                                {
                                    UtilisateurCrt.IsJedi = "1";
                                }
                                if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 4))
                                {
                                    UtilisateurCrt.IsEcommerce = "1";
                                }
                                if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 5))
                                {
                                    UtilisateurCrt.IsCommercialVoyage = "1";
                                }
                                if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 6))
                                {
                                    UtilisateurCrt.IsProductionVoyage = "1";
                                }

                                string strSite = VPLink2013SqlHelper.GetValueReader(Reader, 7);
                                if (strSite.ToLower().Contains("plaine"))
                                {
                                    UtilisateurCrt.IsLaPlaine = "1";
                                }
                                UtilisateurCrt.Pays = VPLink2013SqlHelper.GetValueReader(Reader, 8);
                            }
                            ContextTrace.AddTrace("UtilisateurCrt.Email : " + UtilisateurCrt.Email);
                            ContextTrace.AddTrace("UtilisateurCrt.IsInterne : " + UtilisateurCrt.IsInterne);
                            ContextTrace.AddTrace("UtilisateurCrt.IsManager : " + UtilisateurCrt.IsManager);
                            VPLink2013SqlHelper.CloseReader(conn, Reader);
                            FileSerialization.CreateXmlFromObj(UtilisateurCrt, strFileCacheUtilisateur);
                        }
                    }
                }
            }
        }

        #region get HTML
        /// <summary>
        /// Returns the HTML code rendered by this web part
        /// </summary>
        /// <returns>HTL code as string</returns>
        protected virtual string GetHtml()
        {
            strAction = ParamFrm("MyAction");
            if (string.IsNullOrEmpty(strAction))
            {
                strAction = "liste"; // detail, recherche
            }

            string Source = SPContext.Current.Web.Url;
            ContextTrace.AddTrace("Source : " + Source);
            ContextTrace.AddTrace("GetHtml");
            ContextTrace.AddTrace("GetHtml.strAction by PageName = " + strAction);
            ContextTrace.AddTrace("Context.Utilisateur.Identity.Name : " + this.Context.User.Identity.Name);
            ContextTrace.AddTrace("SPContext.Current.Web.CurrentUser.LoginName : " + SPContext.Current.Web.CurrentUser.LoginName);
            ContextTrace.AddTrace("SPContext.Current.Web.CurrentUser.Name : " + SPContext.Current.Web.CurrentUser.Name);

            global = new GlobalVPLink2013();
            global.Context = new Context();
            global.Context.Action = strAction;

            string Utilisateur = FormatUser(this.Context.User.Identity.Name).ToLower();
            global.Context.CurrentUser = Utilisateur;

            global.Context.SubAction = ParamFrm("SubAction");

            return "VPLink 2013";
        }
        #endregion get HTML

        protected string GetValueConfigurationVP(SPList lst, string key)
        {
            string strValeur = string.Empty;
            SPListItemCollection coll = lst.GetSPListItemCollectionWithTextFields(new List<string>() 
                                        { Fields.ConfigKeyField, 
                                          Fields.ConfigValueField });
            SPListItem item = coll.Cast<SPListItem>()
                                       .Where(x => x.GetItemListFieldValueAsText(Fields.ConfigKeyField).Equals(key, StringComparison.CurrentCultureIgnoreCase))
                                       .FirstOrDefault();
            strValeur = item.GetItemListFieldValueAsText(Fields.ConfigValueField);
            ContextTrace.AddTrace("GetConfigurationVP.strValeur : " + strValeur);
            return strValeur;
        }

        protected string FormatUser(string strUser)
        {
            int iPos = strUser.IndexOf(@"\");
            if (iPos > 0)
            {
                strUser = strUser.Substring(iPos + 1);
            }
            return strUser;
        }

        #region return the value of a parameter in the HTML form or in the page
        /// <summary>
        ///	Uses Request.Form or Request.QueryString
        /// </summary>
        protected string ParamFrm(string Name)
        {
            HttpRequest Request = Context.Request;

            string strValue;
            if (Request.Form.Count == 0)
            {
                strValue = Request.QueryString[Name];
            }
            else
            {
                strValue = Request.Form[Name];
                if (strValue == null || strValue == "undefined")
                {
                    strValue = Request.QueryString[Name];
                }
            }
            if (strValue == null || strValue == "undefined")
            {
                strValue = "";
            }
            strValue = strValue.Trim();

            if (strValue == "")
            {
                strValue = Request.QueryString[Name];
                if (strValue == null || strValue == "undefined")
                {
                    strValue = "";
                }
                strValue = strValue.Trim();
            }

            ContextTrace.AddTrace("ParamFrm : " + Name + " = " + strValue);
            return strValue;
        }

        protected string FormatStringSql(string valeur)
        {
            if (!string.IsNullOrEmpty(valeur))
            {
                return "'" + valeur.Replace("'", "''") + "'";
            }
            else
            {
                return "''";
            }
        }
       
        protected string GetValueAfterSeparator(string Valeur)
        {
            if (string.IsNullOrEmpty(Valeur))
            {
                return string.Empty;
            }
            int iPos = Valeur.IndexOf(";#");
            if (iPos >= 0)
            {
                Valeur = Valeur.Substring(iPos + 2);
            }
            iPos = Valeur.IndexOf(", ");
            if (iPos >= 0)
            {
                Valeur = Valeur.Substring(iPos + 2);
            }
            //AddTrace("GetValueAfterSeparator : " + Valeur);
            return Valeur;
        }
        protected string GetValueBeforeSeparator(string Valeur)
        {
            if (string.IsNullOrEmpty(Valeur))
            {
                return string.Empty;
            }
            int iPos = Valeur.IndexOf(";#");
            if (iPos >= 0)
            {
                Valeur = Valeur.Substring(0, iPos);
            }
            iPos = Valeur.IndexOf(", ");
            if (iPos >= 0)
            {
                Valeur = Valeur.Substring(0, iPos);
            }
            ContextTrace.AddTrace("GetValueAfterSeparator : " + Valeur);
            return Valeur;
        }

        protected string StringAfter(string Text)
        {
            string Separator = @"\";
            if (Text == null)
            {
                return string.Empty;
            }

            Text = Text.ToLower();

            int iPos = Text.IndexOf(Separator);
            if (iPos > 0)
            {
                return Text.Substring(iPos + Separator.Length);
            }
            return Text;
        }

        public string FormatDetailAttachments(SPListItem item, bool delete)
        {
            ContextTrace.AddTrace("FormatDetailAttachments.mstrIdItem : " + item.ID);
            string Value = string.Empty;
            //	Value = "<img src='../images/attach.gif'>";
            SPAttachmentCollection attachments = item.Attachments;
            ContextTrace.AddTrace("FormatDetailAttachments.attachments : " + attachments.Count.ToString());
            //Si nombre de fichiers attachés > 0, afficher ce nombre
            if (attachments.Count > 0)
                Value += "<b>" + attachments.Count + " pièces jointes :</b><br>";
            else
                return string.Empty;

            //Création d'une tableau Html, 1 ligne par fichier attaché, 
            // avec 2 colonnes : 
            //		* nom du fichier avec lien visualisation
            //		* lien suppression
            Value += "<table>";
            for (int i = 0; i < attachments.Count; i++)
            {
                string strZone = item.ParentList.ParentWeb.Url;
                string strList = item.ParentList.Title;
                string strAttachment = attachments[i];
                strAttachment = strAttachment.Replace(@"'", @"\'");

                Value += "<tr><td class='ms-vb'>" +
                    "<a href=\"" + strZone + "/Lists/" + strList + "/Attachments/" + item.ID.ToString() + "/" + attachments[i] + "\">" +
                    attachments[i] +
                    "</a>" +
                    "</td>";
                if (delete)
                {
                    Value += "<td class='ms-propertysheet'>" +
                        "<img alt='Delete' src='/_layouts/images/rect.gif'>&nbsp;" +
                        "<a tabindex=1 href=\"javascript:DeleteAttachment('" + strAttachment + "')\">Delete</a></td>";
                }
                Value += "</tr>";
            }
            Value += "</table>";

            return Value;
        }

        #endregion

        #region control detail
        protected string GetControlLabel(string controlName, string controlValue)
        {
            ContextTrace.AddTrace("GetControlLabel : " + controlName + " = " + controlValue);

            StringBuilder sbControlText = new StringBuilder();
            sbControlText.AppendLine("<span name='" + controlName + "txt' id='" + controlName + "txt'>" + controlValue.Replace("'", "&#39;") + "</span>");
            return sbControlText.ToString() + GetControlHidden(controlName, controlValue);
        }

        protected string GetControlHidden(string controlName, string controlValue)
        {
            ContextTrace.AddTrace("GetControlHidden : " + controlName + " = " + controlValue);

            StringBuilder sbControlText = new StringBuilder();
            sbControlText.AppendLine("<input name='" + controlName + "' id='" + controlName
                + "' type='hidden' value='" + controlValue.Replace("'", "&#39;") + "' title='" + controlName + "' />");
            return sbControlText.ToString();
        }

        protected string GetControlText(string controlName, string controlValue, string size)
        {
            ContextTrace.AddTrace("GetControlText : " + controlName + " = " + controlValue);

            StringBuilder sbControlText = new StringBuilder();
            sbControlText.AppendLine("<input name='" + controlName + "' id='" + controlName
                + "' type='text' value='" + controlValue.Replace("'", "&#39;") + "' size='" + size + "' maxlength='200' title='" + controlName
                + "' class='ms-input' AutoPostBack='0'/>");
            return sbControlText.ToString();
        }

        protected string GetControlText(string controlName, string controlValue, string size, string otherOptions)
        {
            ContextTrace.AddTrace("GetControlText : " + controlName + " = " + controlValue);

            StringBuilder sbControlText = new StringBuilder();
            sbControlText.AppendLine("<input name='" + controlName + "' id='" + controlName
                + "' type='text' value='" + controlValue.Replace("'", "&#39;") + "' size='" + size + "' maxlength='200' title='" + controlName
                + "' class='ms-input' AutoPostBack='0' " + otherOptions + "/>");
            return sbControlText.ToString();
        }

        protected string GetControlText(string controlName, string controlValue)
        {
            return GetControlText(controlName, controlValue.Replace("'", "&#39;"), "40");
        }

        protected string GetControlTextNumeric(string controlName, string controlValue)
        {
            ContextTrace.AddTrace("GetControlTextNumeric : " + controlName + " = " + controlValue);

            StringBuilder sbControlText = new StringBuilder();
            sbControlText.AppendLine("<input name='" + controlName + "' id='" + controlName
                + "' type='text' value='" + controlValue.Replace("'", "&#39;") + "' size='10' maxlength='10' title='" + controlName
                + "' class='ms-input' AutoPostBack='0' onkeypress='javascript:return AcceptOnlyNumbers(event);'/>");
            return sbControlText.ToString();
        }

        protected string GetControlDate(string controlName, string controlValue)
        {
            ContextTrace.AddTrace("GetControlDate : " + controlName + " = " + controlValue);
            StringBuilder sbControlDate = new StringBuilder();
            //sbControlDate.AppendLine("<SCRIPT language='javascript'>g_strDateTimeControlIDs[\"" + controlName + "\"] = \"" + controlName + "\";</SCRIPT>");
            sbControlDate.AppendLine("<table border='0' cellpadding='0' cellspacing='0'>");
            sbControlDate.AppendLine("<tr>");
            sbControlDate.AppendLine("<td class='ms-dtinput' style='white-space: nowrap;'>");
            sbControlDate.AppendLine("<label for='" + controlName + "' style='display:none'>" + controlName + "</label>");
            sbControlDate.AppendLine("<input name='" + controlName + "' type='text' value='" + controlValue + "' size='10' maxlength='10' id='" + controlName + "' title='" + controlName + "' class='ms-input' AutoPostBack='0' onkeypress='javascript:return AcceptOnlyDates(event);'/></td>");
            sbControlDate.AppendLine("</td>");
            sbControlDate.AppendLine("</tr>");
            sbControlDate.AppendLine("</table>");
            return sbControlDate.ToString();
        }

        protected string GetControlSelectOuiNon(string controlName, string controlValue, string otherOptions)
        {
            ContextTrace.AddTrace("GetControlSelectOuiNon : " + controlName + " = " + controlValue);

            StringBuilder sbControlSelect = new StringBuilder();
            sbControlSelect.AppendLine("<select ");
            sbControlSelect.AppendLine("id=\"" + controlName + "\"");
            sbControlSelect.AppendLine("name=\"" + controlName + "\"");
            sbControlSelect.AppendLine(" " + otherOptions);
            sbControlSelect.AppendLine(">");

            sbControlSelect.AppendLine("<option value='Oui'");
            if (controlValue == "Oui")
            {
                sbControlSelect.AppendLine(" selected='true'");
            }
            sbControlSelect.AppendLine(">Oui</option>");

            sbControlSelect.AppendLine("<option value='Non'");
            if (controlValue == "Non")
            {
                sbControlSelect.AppendLine(" selected='true'");
            }
            sbControlSelect.AppendLine(">Non</option>");

            sbControlSelect.AppendLine("</select>");
            return sbControlSelect.ToString();
        }

        protected string GetControlSelect(string controlName, string controlValue, string listValues, string otherOptions)
        {
            ContextTrace.AddTrace("GetControlSelect : " + controlName + " = " + controlValue);

            StringBuilder sbControlSelect = new StringBuilder();
            sbControlSelect.AppendLine("<select ");
            sbControlSelect.AppendLine("id=\"" + controlName + "\"");
            sbControlSelect.AppendLine("name=\"" + controlName + "\"");
            sbControlSelect.AppendLine(" " + otherOptions);
            sbControlSelect.AppendLine(">");

            string[] astrOptions = listValues.Split(char.Parse("/"));
            foreach (string optionLoop in astrOptions)
            {
                string option = optionLoop.Replace("§", "/");
                sbControlSelect.AppendLine("<option");
                sbControlSelect.AppendLine(" value='" + option + "'");
                if (option == controlValue)
                {
                    sbControlSelect.AppendLine(" selected='true'");
                }
                sbControlSelect.AppendLine(">");
                sbControlSelect.AppendLine(option);
                sbControlSelect.AppendLine("</option>");
            }
            sbControlSelect.AppendLine("</select>");
            return sbControlSelect.ToString();
        }

        #endregion control detail

        #region transformation

        protected string GetTransformFromStyleLibrary(string strXml, string strXslt)
        {
            XmlTextReader xtr = new XmlTextReader(new StringReader(strXml));
            XPathDocument xpd = new XPathDocument(xtr);
            xtr.Close();
            XPathNavigator nav = xpd.CreateNavigator();
            StringWriter sw = new StringWriter();
            string Html = string.Empty;
            try
            {
                XslCompiledTransform xslt = new XslCompiledTransform();
                //xslt.Load(strXslPath, new XsltSettings(true, true), new XmlUrlResolver() {  Credentials = new NetworkCredential("clrstrm-admmoss","K$5$40gA") });
                if (!string.IsNullOrEmpty(strXslt))
                {
                    xslt.Load(new XmlTextReader(new StringReader(strXslt)));
                    xslt.Transform(nav, null, sw);
                    Html = sw.ToString();
                }
            }
            catch (System.Xml.Xsl.XsltException exc)
            {
                ContextTrace.AddTrace(string.Format("Erreur XSL : {0} .LineNumber: {1}, LinePosition:{2}", exc.Message, exc.LineNumber, exc.LinePosition));
            }
            catch (System.Exception exc2)
            {
                ContextTrace.AddTrace(string.Format("Erreur XSL : {0}", exc2.Message));
            }
            return Html;
        }
        #endregion

        #region trace / log

        DateTime dtTrace = DateTime.Now;
        protected void AddTraceLine()
        {
            ContextTrace.AddTrace("---------------------");
        }
        /// <summary>
        /// Writes a trace file
        /// </summary>
        /// <param name="FileName">File name</param>
        /// <param name="Body">Content of the file</param>
        protected void TraceFile(string FileName, string Body)
        {
            try
            {
                ContextTrace.AddTrace("TraceFile.FileName : " + FileName);

                using (StreamWriter sw = new StreamWriter(File.Open(FileName, FileMode.Create), Encoding.UTF8))
                {
                    sw.WriteLine(Body);
                }
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Error.TraceFile : " + exc.Message + "/" + exc.StackTrace);
            }
        }

        protected void SaveHtmlTrace(string strHtml)
        {
            try
            {
                string strFile = pathTemp + @"\" + ContextTrace.PrefixFileName + ".htm";
                System.IO.File.WriteAllText(strFile, strHtml);
            }
            catch (System.Exception)
            {
            }
        }

        #endregion
    }
}
